package com.xiaoxu.intranetweb.mybatisplusSzappdb.business.wxInform;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xiaoxu.intranetweb.dom4jUtil.config.SystemConfigReader;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.api.WxFeign;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.api.template.ProcessesApprovalTemplate;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.api.template.TruckOutTemplate;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.api.template.TruckTemplate;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.api.template.BaseTemplate;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.entity.*;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.service.impl.*;
import com.xiaoxu.intranetweb.util.StringUtils;
import com.xiaoxu.intranetweb.util.SzResult;
import feign.FeignException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.time.Duration;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.Arrays;
import java.util.stream.Collectors;

@Component
@Slf4j
public class WxInformBu {
    @Autowired
    private CTrucksServiceImpl cTrucksService;
    @Autowired
    private WxTruckCallServiceImpl wxTruckCallService;
    @Autowired
    private CCompanysServiceImpl companysService;
    @Autowired
    private CProductsInfoServiceImpl productsInfoService;
    @Autowired
    private TPlantsServiceImpl plantsService;
    @Autowired
    private SysUserServiceImpl sysUserService;
    @Autowired
    private SysUserOrgConnServiceImpl sysUserOrgConnService;
    @Autowired
    private SysUserRoleConnServiceImpl sysUserRoleConnService;
    @Autowired
    private SysRoleServiceImpl sysRoleService;
    @Autowired
    private SysUserPartConnServiceImpl sysUserPartConnService;
    @Autowired
    private SysPartServiceImpl sysPartService;
    @Autowired
    private SysUserWxConnServiceImpl sysUserWxConnService;
    @Autowired
    private CSysCfgServiceImpl sysCfgService;
    @Autowired
    private SysDicServiceImpl sysDicService;
    @Autowired
    private WxFeign wxFeign;
    @Autowired
    private CTrucksServiceImpl trucksService;
    @Autowired
    private SystemConfigReader systemConfigReader;
    private long TIME_OUT_PERIOD;
    //车辆叫号通知
//    @Transactional
//    public void truckInform(){
//        QueryWrapper<SysDic> sysDicQueryWrapper = new QueryWrapper<>();
//        sysDicQueryWrapper.eq("DIC_KEY","wx_cell_queue_call");
//        SysDic sysDic = sysDicService.getOne(sysDicQueryWrapper);
//        if (sysDic.getDicVal().equals("1")){
//            //查询请进状态车辆
//            QueryWrapper<CTrucks> cTrucksQueryWrapper = new QueryWrapper<>();
//            cTrucksQueryWrapper.eq("TRUCKS_QUEUE_STATUS",2);
//            List<CTrucks> cTrucks = cTrucksService.list(cTrucksQueryWrapper);
//            //如果请进车辆列表不为空
//            if (StringUtils.isNotEmpty(cTrucks)){
//                //查询全部车辆通知列表
//                List<WxTruckCall> wxTruckCalls = wxTruckCallService.list();
//                //如果全部车辆通知为空即都为需要通知
//                if (StringUtils.isEmpty(wxTruckCalls)){
//                    //循环请进车辆列表
//                    for (CTrucks item : cTrucks) {
//                        setTimeOutPeriod(item.getTrucksCheckinPdt());
//                        addWxTruck(item);
//                    }
//                }else {
//                    //循环请进车辆列表
//                    for (CTrucks cTruck : cTrucks) {
//                        setTimeOutPeriod(cTruck.getTrucksCheckinPdt());
//                        //查询车俩通知列表是否有该车俩通知
//                        WxTruckCall wxTruckCall = hasWxTruckCallWithTruckId(wxTruckCalls, cTruck.getId());
//                        if (wxTruckCall != null){
//                            //有处理超时时间
//                            Duration duration = Duration.between(wxTruckCall.getCallTime(),LocalDateTime.now());
////                            log.info("相差分钟"+duration.toMinutes());
//                            computeTimeOutPeriod(cTruck,duration);
//                        }else {
//                            //没有进行新增
//                            addWxTruck(cTruck);
//                        }
//                    }
//                }
//            }
//        }
//    }
//    //添加车俩通知记录并发送通知
//    public void addWxTruck(CTrucks cTruck){
//        log.info("新增车俩通知");
//        //新建车辆通知空对象
//        WxTruckCall wxTruckCall = new WxTruckCall();
//        //填充车辆通知对象
//        wxTruckCall.setTruckId(cTruck.getId());
//        wxTruckCall.setCallTime(cTruck.getTrucksCallinTm());
//        //新增车辆通知
//        wxTruckCallService.save(wxTruckCall);
//        //建立排队模板发送通知
//        wxTruckInformFeign(cTruck);
//    }
    //计算超时时间
//    public void computeTimeOutPeriod(CTrucks cTruck, Duration duration ){
//        //是否距离超时时间还有10分钟
//        if (TIME_OUT_PERIOD - duration.toMinutes() >= 9 && TIME_OUT_PERIOD- duration.toMinutes() <= 10){
//            log.info("距离超时时间还有10分钟");
//            wxTruckInformFeign(cTruck);
//        }else if (duration.toMinutes() >= TIME_OUT_PERIOD){ //是否已过超时时间
//            log.info("已超时");
//            QueryWrapper<WxTruckCall> wxTruckCallQueryWrapper = new QueryWrapper<>();
//            wxTruckCallQueryWrapper.eq("TRUCK_ID",cTruck.getTrucksId());
//            wxTruckCallService.remove(wxTruckCallQueryWrapper);
//            wxTruckOutInformFeign(cTruck);
//        }
//    }
    //根据设置修改超时时间

    private void setTimeOutPeriod(String id){
        //查询品种类型
        QueryWrapper<CProductsInfo> cProductsInfoQueryWrapper = new QueryWrapper<>();
        cProductsInfoQueryWrapper.eq("ID",id);
        cProductsInfoQueryWrapper.select("PDTINF_CLASS");
        CProductsInfo productsInfo = productsInfoService.getOne(cProductsInfoQueryWrapper);
        QueryWrapper<CSysCfg> cSysCfgQueryWrapper = new QueryWrapper<>();
        cSysCfgQueryWrapper.select("SYSCFG_LONG_VALUE","SYSCFG_STR_VALUE");
        //判断品种类型超时时间类
        if (productsInfo.getPdtinfClass().equals("1")){
            //查询品种类型配置超时时间
            cSysCfgQueryWrapper.eq("SYSCFG_ITEM_NAME","QUCallInToPoundInTmLimitAsh");
            TIME_OUT_PERIOD = sysCfgService.getOne(cSysCfgQueryWrapper).getSyscfgLongValue().longValue();
            //处理超时时间
        } else if (productsInfo.getPdtinfClass().equals("2")) {
            cSysCfgQueryWrapper.eq("SYSCFG_ITEM_NAME","QUCallInToPoundInTmLimitGypsum");
            TIME_OUT_PERIOD = sysCfgService.getOne(cSysCfgQueryWrapper).getSyscfgLongValue().longValue();
        }else if (productsInfo.getPdtinfClass().equals("3") || productsInfo.getPdtinfClass().equals("a45ed1623ea342cc8544f8db17eff1fb") ) {
            cSysCfgQueryWrapper.eq("SYSCFG_ITEM_NAME","QUCallInToPoundInTmLimitCinder");
            TIME_OUT_PERIOD = sysCfgService.getOne(cSysCfgQueryWrapper).getSyscfgLongValue().longValue();
        }else {
            cSysCfgQueryWrapper.eq("SYSCFG_ITEM_NAME","QUCallInToPoundInTmLimit");
            TIME_OUT_PERIOD = sysCfgService.getOne(cSysCfgQueryWrapper).getSyscfgLongValue().longValue();
        }
    }
    //建立排队模板发送通知
    public void wxTruckInformFeign(CTrucks cTruck){
        //        邹县这边只在本地叫号,是否开启微信消息推送功能，0不开启，1开启
        if(systemConfigReader.isWxMsgPush().equals("0")){
            return;
        }
        try {
            QueryWrapper<CTrucks> cTrucksQueryWrapper = new QueryWrapper<>();
            cTrucksQueryWrapper.eq("ID", cTruck.getId());
            cTruck = cTrucksService.getOne(cTrucksQueryWrapper);
            //新建车辆通知模板对象
            TruckTemplate truckTemplate = new TruckTemplate();
            //填充车俩通知模板对象
            QueryWrapper<TPlants> plantsQueryWrapper = new QueryWrapper<>();
            plantsQueryWrapper.select("PLANT_SHORT_NAME");
            plantsQueryWrapper.eq("ID", cTruck.getDataFrom());
            TPlants plants = plantsService.getOne(plantsQueryWrapper);//查询电厂简称
            QueryWrapper<CCompanys> companysQueryWrapper = new QueryWrapper<>();
            companysQueryWrapper.eq("ID", cTruck.getTrucksCheckinCo());
            CCompanys company = companysService.getOne(companysQueryWrapper);//查询排队单位
            truckTemplate.setThing5(plants.getPlantShortName() + "（" + company.getCpyShrtname() + "）");
            QueryWrapper<CProductsInfo> cProductsInfoQueryWrapper = new QueryWrapper<>();
            cProductsInfoQueryWrapper.eq("ID", cTruck.getTrucksCheckinPdt());
            cProductsInfoQueryWrapper.select("PDTINF_PDT");
            CProductsInfo productsInfo = productsInfoService.getOne(cProductsInfoQueryWrapper);//查询品种名称
            truckTemplate.setThing3(productsInfo.getPdtinfPdt() + "（" + cTruck.getTrucksTruckno() + "）");
            truckTemplate.setThing16(StringUtils.isNotEmpty(cTruck.getTrucksCheckinLoadsite())? cTruck.getTrucksCheckinLoadsite() : "不指定装载点");
            truckTemplate.setTime6(cTruck.getTrucksCallinTm().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
            setTimeOutPeriod(cTruck.getTrucksCheckinPdt());
            truckTemplate.setTime12(cTruck.getTrucksCallinTm().plusMinutes(TIME_OUT_PERIOD).format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
            //新建传输通知模板对象
            BaseTemplate baseTemplate = new BaseTemplate();
            //填充传输通知模板data
            baseTemplate.setData(truckTemplate);
            //查询单位权限的用户账号转为wxid填充传输通知模板
            QueryWrapper<SysUserOrgConn> sysUserOrgConnQueryWrapper = new QueryWrapper<>();
            sysUserOrgConnQueryWrapper.eq("ORG_ID", cTruck.getTrucksCheckinCo());
            List<String> wxOpenIds = wxOpenIdList(sysUserOrgConnService.list(sysUserOrgConnQueryWrapper));
            // 使用 Set 来去除重复项

            //循环微信id向不同用户发送通知
            if (StringUtils.isNotEmpty(wxOpenIds)) {
                for (String wxOpenId : wxOpenIds) {
                    baseTemplate.setTouser(wxOpenId);
//                    try {
                        JSONObject inform = wxFeign.truckInform(baseTemplate);
//                        log.info("发送微信车辆叫号信息，"+ inform);
//                    } catch (FeignException e) {//捕获超时异常
//                        log.error("发送微信车辆叫号信息失败");
//                    }

                }
            }
//            else {
//                log.error("发送微信通知失败"+company.getCpyCo() + company.getCpyChico() + "未绑定微信id");
//            }
        }catch (Exception e){
            log.error("发送微信车辆叫号信息失败"+e.getMessage()+ Arrays.toString(e.getStackTrace()));
        }
    }
    //建立排队过号模板发送通知

    public void wxTruckOutInformFeign(CTrucks cTruck){
        //        邹县这边只在本地叫号,是否开启微信消息推送功能，0不开启，1开启
        if(systemConfigReader.isWxMsgPush().equals("0")){
            return;
        }
        try {
            //新建车辆通知模板对象
            TruckOutTemplate truckOutTemplate = new TruckOutTemplate();
            //填充车俩过号通知模板对象
            QueryWrapper<TPlants> plantsQueryWrapper = new QueryWrapper<>();
            plantsQueryWrapper.select("PLANT_SHORT_NAME");
            plantsQueryWrapper.eq("ID", cTruck.getDataFrom());
            TPlants plants = plantsService.getOne(plantsQueryWrapper);//查询电厂简称
            QueryWrapper<CCompanys> companysQueryWrapper = new QueryWrapper<>();
            companysQueryWrapper.eq("ID", cTruck.getTrucksCheckinCo());
            CCompanys company = companysService.getOne(companysQueryWrapper);//查询排队单位
            truckOutTemplate.setThing11(plants.getPlantShortName() + "（" + company.getCpyShrtname() + "）");
            QueryWrapper<CProductsInfo> cProductsInfoQueryWrapper = new QueryWrapper<>();
            cProductsInfoQueryWrapper.eq("ID", cTruck.getTrucksCheckinPdt());
            cProductsInfoQueryWrapper.select("PDTINF_PDT");
            CProductsInfo productsInfo = productsInfoService.getOne(cProductsInfoQueryWrapper);//查询品种名称
            truckOutTemplate.setThing12(productsInfo.getPdtinfPdt());
            truckOutTemplate.setCar_number3(cTruck.getTrucksTruckno());
            truckOutTemplate.setTime9(cTruck.getTrucksCallinTm().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
            setTimeOutPeriod(cTruck.getTrucksCheckinPdt());
            truckOutTemplate.setTime10(cTruck.getTrucksCallinTm().plusMinutes(TIME_OUT_PERIOD).format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
            //新建传输通知模板对象
            BaseTemplate baseTemplate = new BaseTemplate();
            //填充传输通知模板data
            baseTemplate.setData(truckOutTemplate);
            //查询单位权限的用户账号转为wxid填充传输通知模板
            QueryWrapper<SysUserOrgConn> sysUserOrgConnQueryWrapper = new QueryWrapper<>();
            sysUserOrgConnQueryWrapper.eq("ORG_ID", cTruck.getTrucksCheckinCo());
            List<String> wxOpenIds = wxOpenIdList(sysUserOrgConnService.list(sysUserOrgConnQueryWrapper));
            //循环微信id向不同用户发送通知
            if (StringUtils.isNotEmpty(wxOpenIds)) {
                for (String wxOpenId : wxOpenIds) {
                    baseTemplate.setTouser(wxOpenId);
                    try {
                        JSONObject inform = wxFeign.truckOutInform(baseTemplate);
//                        log.info("发送微信排队过号信息，"+inform.toString());
                    } catch (FeignException e) {//捕获超时异常
                        log.error("发送微信排队过号信息失败");
                    }
                }
            }
//            else {
//                log.error("发送微信通知失败"+company.getCpyCo() + company.getCpyChico() + "未绑定微信id");
//            }
        }catch (Exception e){
            log.error("发送微信排队过号信息失败"+e.getMessage()+ Arrays.toString(e.getStackTrace()));
        }
    }
    //返回单位绑定的wxid
    public List<String> wxOpenIdList(List<SysUserOrgConn> list){
        List<String> wxIds = new ArrayList<>();
        QueryWrapper<SysRole> sysRoleQueryWrapper = new QueryWrapper<>();
        sysRoleQueryWrapper.eq("ROLE_CODE","1111");
        SysRole sysRole = sysRoleService.getOne(sysRoleQueryWrapper);
        //过滤 返回有wxId的单位用户
        list.stream().filter((sysUserOrgConn) -> { //过滤 返回有单位权限用户
            QueryWrapper<SysUserRoleConn> sysUserRoleConnQueryWrapper = new QueryWrapper<>();
            sysUserRoleConnQueryWrapper.eq("USER_ID", sysUserOrgConn.getUserId());
            return sysUserRoleConnService.getOne(sysUserRoleConnQueryWrapper).getRoleId().equals(sysRole.getId());
        }).filter(sysUserOrgConn->{
            QueryWrapper<SysUser> sysUserQueryWrapper = new QueryWrapper<>();
            sysUserQueryWrapper.eq("ID",sysUserOrgConn.getUserId());
            sysUserQueryWrapper.eq("DEL_FLAG",0);
            sysUserQueryWrapper.eq("ENABLE_FLAG",1);
            SysUser user = sysUserService.getOne(sysUserQueryWrapper);
            return user != null;
        }).filter((sysUserOrgConn) -> { //过滤 返回有排队权限的用户
            QueryWrapper<SysUserPartConn> sysUserPartConnQueryWrapper = new QueryWrapper<>();
            sysUserPartConnQueryWrapper.eq("USER_ID", sysUserOrgConn.getUserId());
            String partId = sysUserPartConnService.getOne(sysUserPartConnQueryWrapper).getPartId();
            return sysPartService.getById(partId).getPartName().contains("排队");
        }).map((companyUser) -> {
            QueryWrapper<SysUserWxConn> wxConnQueryWrapper = new QueryWrapper<>();
            wxConnQueryWrapper.eq("USER_ID", companyUser.getUserId());
            return sysUserWxConnService.getOne(wxConnQueryWrapper);
        }).filter((wxCompanyUser) -> { //过滤 返回有wxId的单位用户
            return wxCompanyUser != null;
        }).forEach((wxCompanyUser)->{
            wxIds.addAll(Arrays.asList(wxCompanyUser.getWxOpenId().split(","))) ;
        });
        Set<String> uniqueWxOpenIdsSet = new LinkedHashSet<>(wxIds);
        List<String> uniqueWxOpenIds = new ArrayList<>(uniqueWxOpenIdsSet);
        return uniqueWxOpenIds;
    }
    //查询车俩通知列表是否有该车俩通知
    public static WxTruckCall hasWxTruckCallWithTruckId(List<WxTruckCall> wxTruckCalls, String truckId) {
        for (WxTruckCall wxTruckCall : wxTruckCalls) {
            if (wxTruckCall.getTruckId().equals(truckId)) {
                return wxTruckCall;
            }
        }
        return null;
    }

    //发送流程审批通知
    public void processesApprovalInformFeign(String id,String initiationTime,String sponsor){
        try {
            QueryWrapper<SysUserWxConn> wxConnQueryWrapper = new QueryWrapper<>();
            wxConnQueryWrapper.eq("USER_ID", id);
            SysUserWxConn wxConn = sysUserWxConnService.getOne(wxConnQueryWrapper);
            if (wxConn == null) {
                return;
            }
            ProcessesApprovalTemplate processesApprovalTemplate = new ProcessesApprovalTemplate();
            processesApprovalTemplate.setThing6(sponsor);
            processesApprovalTemplate.setTime7(initiationTime);
            BaseTemplate baseTemplate = new BaseTemplate();
            baseTemplate.setTouser(wxConn.getWxOpenId());
            baseTemplate.setData(processesApprovalTemplate);
            JSONObject inform = wxFeign.processesApprovalInform(baseTemplate);
        }catch (Exception e){
            log.error("发送微信车辆叫号信息失败"+e.getMessage()+ Arrays.toString(e.getStackTrace()));
        }
    }

}
